package com.erp.module.crm.xXCrm

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.AdapterView
import androidx.appcompat.app.AlertDialog
import com.erp.Interface.OnUserDataInterface
import com.erp.R
import com.erp.activity.ChaKanTuZhiAvtivity
import com.erp.activityKView.CrmFKView
import com.erp.bean.ClientShouhouBean
import com.erp.myAdapter.FileAdapter
import com.erp.myAdapter.GaugeivGvAdapter1
import com.erp.myFragment.BaseKFragment
import com.erp.permission.PermissionListener
import com.erp.popupwin.PopShejiXiaoshouDuoxuan
import com.erp.util.Dialogutil
import com.erp.util.Httputil
import com.erp.util.Myutil
import com.erp.util.PermissionUtils
import kotlinx.android.synthetic.main.fragment_clientseven.*
import org.json.JSONArray
import org.json.JSONObject


/**
 * Created by Administrator on 2016/12/31/031.
 * 作者：刘洋
 * 售后信息
 */
@SuppressLint("ValidFragment")
class FragmentClientseven : BaseKFragment, View.OnClickListener {
    lateinit var mshouhouBean: ClientShouhouBean ;
    lateinit var FKP : CrmFKView;
    constructor(){
    }
    constructor( FKP: CrmFKView,mshouhouBean: ClientShouhouBean){
        this.mshouhouBean=mshouhouBean
        this.FKP = FKP
    }
    private val f = "FragmentClientseven"
    lateinit var gvfileaapter: FileAdapter
    lateinit var gvaapter: GaugeivGvAdapter1
    private var name: String = ""
    lateinit var updatedialog: AlertDialog
    lateinit var mxuanzhongid : MutableList<String>
    override fun getLayoutId(): Int {
        fragmentname = f
        return R.layout.fragment_clientseven
    }

    fun initView() {
        mxuanzhongid=ArrayList()
        gvfileaapter = FileAdapter(context!!,mshouhouBean.listfile,false)
        GvAssFile.adapter = gvfileaapter
        gvaapter = GaugeivGvAdapter1(mshouhouBean.listimg, activity!!)
        GvAssImg.adapter = gvaapter
        BtBaocun.setOnClickListener(this)
        LlAssPeople.setOnClickListener(this)
        LlAssStartTime.setOnClickListener(this)
        LlAssEndTime.setOnClickListener(this)
    }

    override fun initData() {
        initView()
        initClick()
        initDatas()
    }

    private fun initDatas() {
        Myutil.settv(mshouhouBean.ass_asp, EtAssAsp)
        val sb = StringBuffer("")
        val sp = mshouhouBean.ass_people
        for (i in sp.indices) {
            if (sp[i] != "") {
                if (i < sp.size - 1) {
                    sb.append(sp[i]).append("\n")
                }else{
                    sb.append(sp[i])
                }
            }
        }
        Myutil.settv(sb.toString(), TvAssPeople)
        Myutil.settv(mshouhouBean.ass_tel, EtAssTel)
        Myutil.settv(Myutil.getdata(mshouhouBean.ass_start_time), TvAssStartTime)
        Myutil.settv(Myutil.getdata(mshouhouBean.ass_end_time), TvAssEndTime)
        if (!isFirstLoad) {
            gvfileaapter.Allnotify(mshouhouBean.listfile)
            gvaapter.Allnotify(mshouhouBean.listimg)
        }
    }


    fun initClick() {
      /**
       * 删除图片
       */
      GvAssImg.onItemLongClickListener = AdapterView.OnItemLongClickListener { parent, view, position, id ->
          if(position<mshouhouBean.listimg.size) {
              val listid = ArrayList<String>()
              for (i in 0 until mshouhouBean.listfileid.size) {
                  if (mshouhouBean.listfileid[i] != mshouhouBean.listimg[position].imgid) {
                      listid.add(mshouhouBean.listfileid[i])
                  }
              }
              val jo=xiugai()
              Dialogutil.longitem(activity, listid, "ass",jo,FKP)
              true
          }else{
              true
          }
      }
      /**
       * 查看图片
       */
      GvAssImg.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
          if(position<mshouhouBean.listimg.size) {
              val intent = Intent(activity, ChaKanTuZhiAvtivity::class.java)
              val urls : ArrayList<String> = ArrayList()
              urls.add(mshouhouBean.listimg[position].imguri)
              intent.putStringArrayListExtra("url", urls)
              startActivity(intent)
          }else if(mshouhouBean.listimg.size==position){
              Dialogutil.photodialog(activity, this@FragmentClientseven)
          }
      }
      /**
       * 下载附件
       */
      GvAssFile.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
          PermissionUtils.isupdate(activity!!, object : PermissionListener {
              override fun onSucceed(requestCode: Int, grantPermissions: List<String>) {
                  Dialogutil.downloaddialog1(mshouhouBean.listfile[position], activity)
              }

              override fun onFailed(requestCode: Int, deniedPermissions: List<String>) {
                  Myutil.MyTost("没有权限，无法下载")
              }
          })
      }
    }
    override fun onClick(v: View?) {
        when(v){
            BtBaocun->{
                val jo=xiugai()
                if(!Myutil.isTel(EtAssTel.text.toString())){
                    Myutil.MyTost("输入正确的电话号码")
                    return
                }
                updatedialog= Myutil.showupdatedialog(context, "正在上传图片", false)
                Httputil.cleanclient(activity, ClientKActivity.getid(),jo,object : OnUserDataInterface {
                    override fun onUserData(data: String?) {
                        updatedialog.dismiss()
                        Myutil.longlogshow("TAAG","jdata="+Myutil.decodeUnicode(data))
                        if(data==null){
                            return
                        }
                        FKP.updata(data)
                    }

                    override fun onNot(throwable: String?) {
                        updatedialog.dismiss()
                        Log.d("TAAAG","throwable="+throwable)
                    }

                })
            }
            LlAssPeople -> {
                val  pop = PopShejiXiaoshouDuoxuan(context!!,PopShejiXiaoshouDuoxuan.XSY,mshouhouBean.ass_people,object : PopShejiXiaoshouDuoxuan.duoxuan{
                    override fun xuanze(list: MutableList<String>, listid: MutableList<String>) {
                        val shejishi = StringBuffer("")
                        for (j in 0 until list.size) {
                            if (j == list.size - 1) {
                                shejishi.append(list[j])
                            } else {
                                shejishi.append(list[j])
                                shejishi.append("\n")
                            }
                        }
                        Myutil.settv(shejishi.toString(), TvAssPeople)
                        mxuanzhongid=listid
                    }

                },"请选择设计师")
                pop.show(sp,TvAssPeople)
            }
            LlAssStartTime -> {
                Dialogutil.showBottoPopupWindow(TvAssStartTime, "选择售后开始时间", TvAssStartTime.text.toString(), activity)
            }
            LlAssEndTime -> {
                Dialogutil.showBottoPopupWindow(TvAssEndTime, "选择售后开始时间", TvAssEndTime.text.toString(), activity)
            }
        }
    }
    private fun xiugai(): JSONObject {
        var jo = JSONObject()
        try {
            val ass = JSONObject()
            ass.put("ass_tel", EtAssTel.text.toString())
            ass.put("ass_start_time", TvAssStartTime.text.toString())
            ass.put("ass_end_time", TvAssEndTime.text.toString())
            ass.put("ass_asp", EtAssAsp.text.toString())
            if(TvAssPeople.text.toString()!=""&&mxuanzhongid.size>0) {
                val js = JSONArray()
                for (s in mxuanzhongid) {
                    js.put(s)
                }
                ass.put("after_sales_server", js)
            }
            jo.put("ass", ass)
        } catch (e: Exception) {
            e.printStackTrace()
            Log.d("TAAAG", "--------------" + e.toString())
        }

        return jo
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(data==null){
            return
        }
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                100 -> {
                    name = data.getStringExtra("dir")
                    val listid = ArrayList<String>()
                    for (i in 0 until mshouhouBean.listimg.size) {
                        listid.add(mshouhouBean.listimg[i].imgid)
                    }
                    val jo=xiugai()
                    Dialogutil.previewdialog(activity, mshouhouBean.listfileid, name, "ass",jo, FKP)
                }
                99 -> {
                    val selectedImage = data.data
                    val filePathColumns = arrayOf(MediaStore.Images.Media.DATA)
                    if(selectedImage != null){
                        val c = context!!.contentResolver.query(selectedImage, filePathColumns, null, null, null)
                        c!!.moveToFirst()
                        val columnIndex = c.getColumnIndex(filePathColumns[0])
                        val imagePath = c.getString(columnIndex)
                        val listid = ArrayList<String>()
                        for (i in 0 until mshouhouBean.listimg.size) {
                            listid.add(mshouhouBean.listimg[i].imgid)
                        }
                        val jo=xiugai()
                        Dialogutil.previewdialog(activity, mshouhouBean.listfileid, imagePath, "ass",jo, FKP)
                    }

                }
            }
        }
    }

    fun notifydata() {
        initDatas()
    }


}
